#include "authwidget.h"
#include "cryptstring.h"
#include "tools.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QFont>
#include <QMessageBox>
#include <QDebug>

AuthWidget::AuthWidget(QWidget *parent)
    : QWidget(parent)
{
    // 初始化TCP套接字
    clientTcpSocket = new MyTcpSocket(this);
    QString ip("192.168.88.130");
    quint16 port(8000);
    clientTcpSocket->connectToHost(ip, port);

    // 初始化UI
    initUI();
    initConnections();

    // 连接服务器信号
    connect(clientTcpSocket, &MyTcpSocket::connected, [=](){
        qDebug() << "连接成功！";
        QMessageBox::information(this, "提示", "连接成功！");
    });

    connect(clientTcpSocket, &MyTcpSocket::disconnected, [=](){
        qDebug() << "连接断开！";
        QMessageBox::information(this, "提示", "连接断开！");
    });

    // 连接数据包处理信号
    connect(clientTcpSocket, &MyTcpSocket::readPacketFinished, this, &AuthWidget::handleLoginPacket);
    connect(clientTcpSocket, &MyTcpSocket::readPacketFinished, this, &AuthWidget::handleSignupPacket);
}

AuthWidget::~AuthWidget()
{
    // 清理资源
}

void AuthWidget::initUI()
{
    this->setWindowTitle("智慧监控系统");
    setMaximumSize(400, 350);
    setMinimumSize(400, 350);

    // 创建堆栈窗口
    stackedWidget = new QStackedWidget(this);

    // 创建登录页面
    loginPage = new QWidget();
    QVBoxLayout *loginLayout = new QVBoxLayout(loginPage);

    QFont font;
    font.setFamily("等线");
    font.setPointSize(15);

    // 用户名输入框
    QHBoxLayout *usernameLayout = new QHBoxLayout();
    QLabel *usernameLabel = new QLabel("    账号:");
    loginUsername = new QLineEdit();
    loginUsername->setMinimumHeight(30);
    loginUsername->setMaximumWidth(300);
    loginUsername->setAlignment(Qt::AlignHCenter);
    loginUsername->setFont(font);
    loginUsername->setMaxLength(20);
    usernameLayout->addStretch(1);
    usernameLayout->addWidget(usernameLabel);
    usernameLayout->addWidget(loginUsername);
    usernameLayout->addStretch(1);

    // 密码输入框
    QHBoxLayout *passwordLayout = new QHBoxLayout();
    QLabel *passwordLabel = new QLabel("    密码:");
    loginPassword = new QLineEdit();
    loginPassword->setMinimumHeight(30);
    loginPassword->setMaximumWidth(300);
    loginPassword->setAlignment(Qt::AlignHCenter);
    loginPassword->setFont(font);
    loginPassword->setEchoMode(QLineEdit::Password);
    passwordLayout->addStretch(1);
    passwordLayout->addWidget(passwordLabel);
    passwordLayout->addWidget(loginPassword);
    passwordLayout->addStretch(1);

    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    loginButton = new QPushButton("登录");
    loginButton->setMinimumSize(80, 40);
    loginButton->setMaximumWidth(100);

    toRegisterButton = new QPushButton("注册");
    toRegisterButton->setMinimumSize(80, 40);
    toRegisterButton->setMaximumWidth(100);

    buttonLayout->addWidget(loginButton);
    buttonLayout->addWidget(toRegisterButton);

    // 添加到登录页面布局
    loginLayout->addStretch(1);
    loginLayout->addLayout(usernameLayout);
    loginLayout->addLayout(passwordLayout);
    loginLayout->addLayout(buttonLayout);
    loginLayout->addStretch(1);

    // 创建注册页面
    registerPage = new QWidget();
    QVBoxLayout *registerLayout = new QVBoxLayout(registerPage);

    // 用户名输入框
    QHBoxLayout *regUsernameLayout = new QHBoxLayout();
    QLabel *regUsernameLabel = new QLabel("    账号:");
    registerUsername = new QLineEdit();
    registerUsername->setMinimumHeight(30);
    registerUsername->setMaximumWidth(300);
    registerUsername->setAlignment(Qt::AlignHCenter);
    registerUsername->setFont(font);
    registerUsername->setMaxLength(20);
    regUsernameLayout->addStretch();
    regUsernameLayout->addWidget(regUsernameLabel);
    regUsernameLayout->addWidget(registerUsername);
    regUsernameLayout->addStretch();

    // 密码输入框
    QHBoxLayout *regPasswordLayout = new QHBoxLayout();
    QLabel *regPasswordLabel = new QLabel("    密码:");
    registerPassword = new QLineEdit();
    registerPassword->setMinimumHeight(30);
    registerPassword->setMaximumWidth(300);
    registerPassword->setAlignment(Qt::AlignHCenter);
    registerPassword->setFont(font);
    registerPassword->setEchoMode(QLineEdit::Password);
    regPasswordLayout->addStretch();
    regPasswordLayout->addWidget(regPasswordLabel);
    regPasswordLayout->addWidget(registerPassword);
    regPasswordLayout->addStretch();

    // 确认密码输入框
    QHBoxLayout *regPasswordConfirmLayout = new QHBoxLayout();
    QLabel *regPasswordConfirmLabel = new QLabel("确认密码:");
    registerPasswordConfirm = new QLineEdit();
    registerPasswordConfirm->setMinimumHeight(30);
    registerPasswordConfirm->setMaximumWidth(300);
    registerPasswordConfirm->setAlignment(Qt::AlignHCenter);
    registerPasswordConfirm->setFont(font);
    registerPasswordConfirm->setEchoMode(QLineEdit::Password);
    regPasswordConfirmLayout->addStretch();
    regPasswordConfirmLayout->addWidget(regPasswordConfirmLabel);
    regPasswordConfirmLayout->addWidget(registerPasswordConfirm);
    regPasswordConfirmLayout->addStretch();

    // 按钮布局
    QHBoxLayout *regButtonLayout = new QHBoxLayout();
    registerButton = new QPushButton("注册");
    registerButton->setMinimumSize(80, 40);
    registerButton->setMaximumWidth(100);

    toLoginButton = new QPushButton("返回登录");
    toLoginButton->setMinimumSize(80, 40);
    toLoginButton->setMaximumWidth(100);

    regButtonLayout->addWidget(registerButton);
    regButtonLayout->addWidget(toLoginButton);

    // 添加到注册页面布局
    registerLayout->addStretch();
    registerLayout->addLayout(regUsernameLayout);
    registerLayout->addLayout(regPasswordLayout);
    registerLayout->addLayout(regPasswordConfirmLayout);
    registerLayout->addLayout(regButtonLayout);
    registerLayout->addStretch();

    // 将页面添加到堆栈
    stackedWidget->addWidget(loginPage);
    stackedWidget->addWidget(registerPage);
    stackedWidget->setCurrentIndex(0); // 默认显示登录页面

    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(stackedWidget);
}

void AuthWidget::initConnections()
{
    // 登录页面连接
    connect(loginButton, &QPushButton::clicked, this, &AuthWidget::handleLogin);
    connect(toRegisterButton, &QPushButton::clicked, this, &AuthWidget::switchToRegister);

    // 注册页面连接
    connect(registerButton, &QPushButton::clicked, this, &AuthWidget::handleRegister);
    connect(toLoginButton, &QPushButton::clicked, this, &AuthWidget::switchToLogin);
}

void AuthWidget::handleLogin()
{
    QString username = loginUsername->text();
    QString password = loginPassword->text();

    if(username.isEmpty() || password.isEmpty()){
        QMessageBox::information(this, "错误", "账号或密码为空！");
        return;
    }

    // 发送登录请求
    clientTcpSocket->sendTLV(TASK_LOGIN_SECTION1, username.size(), username.toUtf8().data());
}

void AuthWidget::handleRegister()
{
    QString username = registerUsername->text();
    QString password = registerPassword->text();
    QString password2 = registerPasswordConfirm->text();

    if(username.isEmpty() || password.isEmpty() || password2.isEmpty()){
        QMessageBox::information(this, "错误", "账号或密码为空！");
        return;
    }

    if(password != password2){
        QMessageBox::information(this, "错误", "两次密码不一致~");
        return;
    }

    // 发送注册请求
    clientTcpSocket->sendTLV(TASK_SIGNUP_SECTION1, username.size(), username.toUtf8().data());
}

void AuthWidget::handleLoginPacket(const Packet& packet)
{
    qDebug() << "登录界面处理接受数据";
    int type = packet._type;
    QString info;

    switch (type){
    case TASK_LOGIN_SECTION1_RESP_OK: // 用户存在，则发送密文
    {
        QByteArray train = getTrainMessage(loginUsername->text(), packet._msg);
        clientTcpSocket->sendTLV(TASK_LOGIN_SECTION2, train.length(), train.data());
        return;
    }
    case TASK_LOGIN_SECTION1_RESP_ERROR:
        info = "用户不存在或账号错误";
        break;
    case TASK_LOGIN_SECTION2_RESP_OK:
        info = "登录成功";
        // 这里可以添加登录成功后的操作，如打开主界面
        break;
    case TASK_LOGIN_SECTION2_RESP_ERROR:
        info = "密码错误";
        break;
    default: // 如果不属于以上消息，说明不是登录需要处理的消息
        return;
    }

    QMessageBox::information(this, "提示", info);
}

void AuthWidget::handleSignupPacket(const Packet& packet)
{
    qDebug() << "注册界面处理接受数据";
    int type = packet._type;
    QString info;

    switch (type){
    case TASK_SIGNUP_SECTION1_RESP_OK: // 用户存在，则发送密文
    {
        QByteArray train = getTrainMessage(registerUsername->text(), packet._msg);
        clientTcpSocket->sendTLV(TASK_SIGNUP_SECTION2, train.length(), train.data());
        return;
    }
    case TASK_SIGNUP_SECTION1_RESP_ERROR:
        info = "账号已存在";
        break;
    case TASK_SIGNUP_SECTION2_RESP_OK:
        info = "注册成功";
        // 注册成功后自动切换到登录页面
        switchToLogin();
        break;
    case TASK_SIGNUP_SECTION2_RESP_ERROR:
        info = "注册失败";
        break;
    default: // 如果不属于以上消息，说明不是注册需要处理的消息
        return;
    }

    QMessageBox::information(this, "提示", info);
}

void AuthWidget::switchToLogin()
{
    stackedWidget->setCurrentIndex(0); // 切换到登录页面
    // 清空注册页面的输入
    registerUsername->clear();
    registerPassword->clear();
    registerPasswordConfirm->clear();
}

void AuthWidget::switchToRegister()
{
    stackedWidget->setCurrentIndex(1); // 切换到注册页面
    // 清空登录页面的输入
    loginUsername->clear();
    loginPassword->clear();
}
